/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p3as.cliente;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Josue
 */
public class ScoreConnection implements ScoreSaver{

    String location;
    URL url;
    URLConnection connection;
    
    @Override
    public Ranking saveScore(String user, int score) {
        try {
            takeConnection();
            OutputStream ostream = connection.getOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(ostream);
            //o.writeObject(user);
            o.writeObject(score);
            o.flush();
            o.close();
            
            InputStream istream = connection.getInputStream();
            ObjectInputStream i = new ObjectInputStream(istream);
            Ranking ranking = (Ranking) i.readObject();
            i.close();
            return ranking;
        } catch (Exception ex) {
            Logger.getLogger(ScoreConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }   
        
    public void takeConnection() throws IOException{
        location = "http://localhost:8080/P3AS-Servidor/ScoreServlet";
        url = new URL(location);
        connection = url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    }  
}
